use core::fmt::{Write, Arguments};
use crate::sys_call::sys_write;
use crate::sbi_call;

const STDOUT:usize=1;
struct SysStdout;

impl Write for SysStdout {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        sys_write(STDOUT, s.as_bytes());
        Ok(())
    }
}

pub struct SbiStdout;

impl Write for SbiStdout {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        for c in s.chars() {
            sbi_call::console_put_char(c as usize);
        }
        Ok(())
    }
}

pub fn print(args: Arguments) {
    SbiStdout.write_fmt(args).unwrap();
}

#[macro_export]
macro_rules! print {
    ($fmt: literal $(, $($arg: tt)+)?) => {
        $crate::console::print(format_args!($fmt $(, $($arg)+)?));
    }
}

#[macro_export]
macro_rules! println {
    ($fmt: literal $(, $($arg: tt)+)?) => {
        $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
    }
}